from PySide6.QtWidgets import QTabWidget, QVBoxLayout, QWidget, QToolBar, QLabel, QPushButton, QHBoxLayout, QScrollArea, QFrame, QGridLayout, QLayout, QSizePolicy
from PySide6.QtCore import Qt, Signal, QSize, QRect, QPoint
from PySide6.QtGui import QIcon
import os
from .default_icons import get_default_icon

# 添加FlowLayout支持水平流布局
class FlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super().__init__(parent)
        
        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)
            
        self.setSpacing(spacing)
        
        self._item_list = []
        
    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)
            
    def addItem(self, item):
        self._item_list.append(item)
        
    def count(self):
        return len(self._item_list)
        
    def itemAt(self, index):
        if 0 <= index < len(self._item_list):
            return self._item_list[index]
        return None
        
    def takeAt(self, index):
        if 0 <= index < len(self._item_list):
            return self._item_list.pop(index)
        return None
        
    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))
        
    def hasHeightForWidth(self):
        return True
        
    def heightForWidth(self, width):
        height = self._do_layout(QRect(0, 0, width, 0), True)
        return height
        
    def setGeometry(self, rect):
        super().setGeometry(rect)
        self._do_layout(rect, False)
        
    def sizeHint(self):
        return self.minimumSize()
        
    def minimumSize(self):
        size = QSize()
        
        for item in self._item_list:
            size = size.expandedTo(item.minimumSize())
            
        size += QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top())
        return size
        
    def _do_layout(self, rect, test_only):
        x = rect.x()
        y = rect.y()
        line_height = 0
        spacing = self.spacing()
        
        for item in self._item_list:
            # 增加工具栏之间的间距
            space_x = spacing + 15  # 增大水平间距
            space_y = spacing + 10  # 增大垂直间距
            
            next_x = x + item.sizeHint().width() + space_x
            if next_x - space_x > rect.right() and line_height > 0:
                x = rect.x()
                y = y + line_height + space_y
                next_x = x + item.sizeHint().width() + space_x
                line_height = 0
                
            if not test_only:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
                
            x = next_x
            line_height = max(line_height, item.sizeHint().height())
            
        return y + line_height - rect.y()

class ToolbarContainer(QWidget):
    """工具栏容器，包含工具栏名称和工具栏本身"""
    def __init__(self, name, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(5, 0, 5, 0)
        self.layout.setSpacing(2)
        
        # 创建一个水平布局来容纳分隔线和工具栏
        container = QWidget()
        h_layout = QHBoxLayout(container)
        h_layout.setContentsMargins(0, 0, 0, 0)
        h_layout.setSpacing(5)
        
        # 创建左侧分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.VLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet("background-color: #cccccc;")
        separator.setFixedWidth(1)
        h_layout.addWidget(separator)
        
        # 创建工具栏
        self.toolbar = QToolBar()
        self.toolbar.setObjectName(name)
        self.toolbar.setMovable(False)
        self.toolbar.setFloatable(False)
        h_layout.addWidget(self.toolbar)
        
        # 将水平布局容器添加到主布局
        self.layout.addWidget(container)
        
        # 创建工具栏名称标签
        self.name_label = QLabel(name)
        self.name_label.setAlignment(Qt.AlignCenter)
        self.name_label.setStyleSheet("QLabel { color: #555; font-size: 11px; }")
        
        # 添加标签到布局
        self.layout.addWidget(self.name_label)
        
        # 设置固定宽度，确保在流布局中有合适的尺寸
        self.setMinimumWidth(100)
        self.setMaximumWidth(250)
        
        # 设置样式，添加边框效果
        self.setStyleSheet("""
            QToolBar {
                border: none;
                background-color: transparent;
            }
        """)
        
    def addWidget(self, widget):
        """添加部件到工具栏"""
        self.toolbar.addWidget(widget)
        
    def addAction(self, action):
        """添加动作到工具栏"""
        self.toolbar.addAction(action)


class CustomTabWidget(QWidget):
    """自定义标签页控件，替代菜单栏，每个标签包含相关工具栏"""
    
    # 定义信号，当展开/折叠状态改变时发出
    collapseStateChanged = Signal(bool)  # 传递当前是否是折叠状态
    
    def __init__(self, parent=None):
        super().__init__(parent)
        
        # 设置对象名称，方便样式表定位
        self.setObjectName("TabWidgetContainer")
        
        # 创建布局
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.North)
        self.tab_widget.setDocumentMode(True)  # 使用文档模式，外观更现代
        
        # 添加到布局
        self.layout.addWidget(self.tab_widget)
        
        # 创建分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet("background-color: #cccccc;")
        separator.setFixedHeight(1)
        self.layout.addWidget(separator)
        
        # 初始化数据
        self.toolbars = {}  # 存储每个标签页中的工具栏
        self.is_collapsed = False
        
        # 设置固定高度属性，确保不受DockWidget影响
        self.setMinimumHeight(150)
        
        # 添加折叠/展开按钮
        self.setupCollapseButton()
        
        # 设置样式，确保顶部位置
        self.setStyleSheet("""
            #TabWidgetContainer {
                background-color: white;
            }
        """)
        
    def setupCollapseButton(self):
        """设置折叠/展开按钮"""
        # 创建角落部件
        corner_widget = QWidget()
        corner_layout = QHBoxLayout(corner_widget)
        corner_layout.setContentsMargins(0, 0, 6, 0)  # 增加右边距
        corner_layout.setSpacing(2)
        
        # 获取折叠图标
        collapse_icon = get_default_icon("collapse")
        
        # 创建按钮
        self.collapse_button = QPushButton()
        self.collapse_button.setIcon(collapse_icon)
        self.collapse_button.setToolTip("折叠/展开")
        self.collapse_button.setFlat(True)
        self.collapse_button.setFixedSize(QSize(20, 20))
        self.collapse_button.setCursor(Qt.PointingHandCursor)  # 设置鼠标样式为手型
        self.collapse_button.clicked.connect(self.toggleCollapse)
        
        # 添加按钮到角落布局
        corner_layout.addWidget(self.collapse_button)
        
        # 设置角落部件
        self.tab_widget.setCornerWidget(corner_widget, Qt.TopRightCorner)
        
    def addTab(self, label):
        """添加一个标签页"""
        # 创建容器部件
        tab_widget = QWidget()
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QScrollArea.NoFrame)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        # 创建内容部件
        content_widget = QWidget()
        content_widget.setStyleSheet("""
            background-color: #f8f8f8;
            border-radius: 4px;
            padding: 5px;
        """)
        self.toolbars[label] = {}  # 初始化工具栏字典
        
        # 创建流布局，使工具栏横向排布
        content_layout = FlowLayout(content_widget)
        content_layout.setSpacing(15)  # 设置更大的间距
        
        # 设置滚动区域
        scroll_area.setWidget(content_widget)
        
        # 设置标签页布局
        tab_layout = QVBoxLayout(tab_widget)
        tab_layout.setContentsMargins(10, 10, 10, 10)  # 增加内边距
        tab_layout.addWidget(scroll_area)
        
        # 添加到Tab控件
        idx = self.tab_widget.addTab(tab_widget, label)
        
        return content_layout, idx
        
    def addToolbar(self, tab_label, toolbar_name):
        """添加工具栏到指定标签页"""
        # 检查标签页是否存在
        if tab_label not in self.toolbars:
            content_layout, _ = self.addTab(tab_label)
        else:
            content_layout = None
            for i in range(self.tab_widget.count()):
                if self.tab_widget.tabText(i) == tab_label:
                    content_layout = self.tab_widget.widget(i).findChild(QScrollArea).widget().layout()
                    break
        
        # 创建工具栏容器
        toolbar_container = ToolbarContainer(toolbar_name)
        
        # 添加到布局
        if content_layout is not None:
            content_layout.addWidget(toolbar_container)
            
        # 保存工具栏引用
        self.toolbars[tab_label][toolbar_name] = toolbar_container
        
        return toolbar_container
        
    def getToolbar(self, tab_label, toolbar_name):
        """获取指定标签页的指定工具栏"""
        return self.toolbars.get(tab_label, {}).get(toolbar_name)
        
    def toggleCollapse(self):
        """切换折叠/展开状态"""
        self.is_collapsed = not self.is_collapsed
        
        # 修改图标
        if self.is_collapsed:
            self.collapse_button.setIcon(get_default_icon("expand"))
            
            # 只隐藏内容部分，保持标签栏可见
            for i in range(self.tab_widget.count()):
                widget = self.tab_widget.widget(i)
                if widget:
                    # 隐藏滚动区域
                    scroll_area = widget.findChild(QScrollArea)
                    if scroll_area:
                        scroll_area.hide()
            
            # 设置最小和最大高度为标签栏高度
            tabbar_height = self.tab_widget.tabBar().height()
            self.setFixedHeight(tabbar_height + 2)  # 标签栏高度加上边框
        else:
            self.collapse_button.setIcon(get_default_icon("collapse"))
            
            # 显示内容部分
            for i in range(self.tab_widget.count()):
                widget = self.tab_widget.widget(i)
                if widget:
                    # 显示滚动区域
                    scroll_area = widget.findChild(QScrollArea)
                    if scroll_area:
                        scroll_area.show()
            
            # 恢复高度限制
            self.setMinimumHeight(150)
            self.setMaximumHeight(16777215)  # Qt的最大值
        
        # 发出信号，通知主窗口调整布局
        self.collapseStateChanged.emit(self.is_collapsed)
        
        # 确保立即更新界面
        self.update()
        self.tab_widget.update() 